package cn.felord.verse.configure;

import cn.felord.common.utils.AuthenticationUtil;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.DataPermissionInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.apache.ibatis.reflection.MetaObject;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.Instant;

/**
 * Mybatis plus configuration.
 *
 * @author n1
 */
@MapperScan("cn.felord.app.mapper")
@Configuration(proxyBeanMethods = false)
public class MybatisPlusConfiguration {
    /**
     * Mybatis plus interceptor.
     *
     * @return mybatis plus interceptor
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }

    @Bean
    DataPermissionInterceptor dataPermissionInterceptor(){
        return new DataPermissionInterceptor();
    }


    /**
     * Mybatis audit handler
     *
     * @return the metaObjectHandler
     */
    @Bean
    public MetaObjectHandler mybatisAuditHandler() {
        return new MetaObjectHandler() {
            @Override
            public void insertFill(MetaObject metaObject) {
                this.strictInsertFill(metaObject, "creator", String.class, AuthenticationUtil.currentUserName());
                this.strictInsertFill(metaObject, "createTime", Instant.class, Instant.now());
            }

            @Override
            public void updateFill(MetaObject metaObject) {
                this.strictUpdateFill(metaObject, "updater", String.class, AuthenticationUtil.currentUserName());
                this.strictUpdateFill(metaObject, "updateTime", Instant.class, Instant.now());
            }
        };
    }

}
